import pool from "@/lib/db";

const navigationModule = {
  get: async (conn = pool) => {
    const sql = `SELECT * FROM navigations`;
    const [result] = await conn.query(sql);
    return result;
  },
  getById: async (id, conn = pool) => {
    const sql = `SELECT * FROM navigations WHERE id = ?`;
    const [result] = await conn.query(sql, [id]);
    return result[0];
  },
  add: async ({ status, name, description, url, icon, position, sort, parent_id }, conn = pool) => {
    const sql = `INSERT INTO navigations (status, name, description, url, icon, position, sort, parent_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`;
    const [result] = await conn.query(sql, [status, name, description, url, icon, position, sort, parent_id]);
    return result.insertId;
  },
  update: async ({ id, status, name, description, url, icon, position, sort, parent_id }, conn = pool) => {
    const sql = `UPDATE navigations SET status = ?, name = ?, description = ?, url = ?, icon = ?, position = ?, sort = ?, parent_id = ? WHERE id = ?`;
    const [result] = await conn.query(sql, [status, name, description, url, icon, position, sort, parent_id, id]);
    return result.affectedRows;
  },
  deleteById: async (id, conn = pool) => {
    let sql;
    let params;
    if (Array.isArray(id)) {
      if (id.length === 0) return 0;
      sql = `DELETE FROM navigations WHERE id IN (${'?'.repeat(id.length).split('').join(',')})`;
      params = id;
    } else if (typeof id === 'number') {
      sql = `DELETE FROM navigations WHERE id = ?`;
      params = [id];
    } else {
      throw new Error('Invalid id parameter type');
    }
    const [result] = await conn.query(sql, params);
    return result.affectedRows;
  }
}

export default navigationModule;